<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form size="large" ref="formRef" :model="formData" :rules="formRules" label-width="100px"
      v-loading="formLoading">

      <el-form-item label="产品ID" prop="productId">
        <el-input v-model="formData.productId" placeholder="请输入" />
      </el-form-item>


      <el-form-item label="表名" prop="tableName">
        <el-input v-model="formData.tableName" placeholder="请输入表名" />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio v-for="item in devTypeOptions" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="时间戳类型" prop="timeField">
        <el-input v-model="formData.timeField" placeholder="请输入" />
      </el-form-item>

      <!-- <el-form-item label="忽略字段" prop="ignoreField">
        <el-input v-model="formData.ignoreField" placeholder="请输入忽略存储到数据库的字段" />
      </el-form-item> -->
      <el-tooltip content="输入完成后按回车键进行分割" placement="top">
        <el-form-item label="忽略字段" prop="ignoreField">
          <el-input-tag v-model="formData.ignoreField" draggable placeholder="请输入忽略字段,按回车分隔" delimiter="," />
        </el-form-item>
      </el-tooltip>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ProductTableMappingApi, ProductTableMapping } from '@/api/business/producttablemapping'

/** 产品表名映射 表单 */
defineOptions({ name: 'ProductTableMappingForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 定义设备类型选项（写死）
const devTypeOptions = [
  { label: 'file', value: 'file' },
  { label: 'ammeter', value: 'ammeter' }
]


// 默认值：file
const DEFAULT_DEVTYPE = 'file'

const formData = ref({
  productId: undefined,
  tableName: undefined,
  type: DEFAULT_DEVTYPE,
  timeField: undefined,
  ignoreField: [] as string[],
})
const formRules = reactive({
  tableName: [{ required: true, message: '表名不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '类型：daily/file不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await ProductTableMappingApi.getProductTableMapping(id)

      // ✅ 回显时：如果 ignoreField 是字符串，就 split 成数组
      formData.value = {
        ...data,
        ignoreField: Array.isArray(data.ignoreField)
          ? data.ignoreField
          : (data.ignoreField ? data.ignoreField.split(',').map(s => s.trim()) : [])
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    // ✅ 提交前：创建副本，将 ignoreField 从 string[] 转为 string
    const submitData = {
      ...formData.value,
      ignoreField: formData.value.ignoreField.join(',') // ['a','b'] → 'a,b'
    } as unknown as ProductTableMapping

    if (formType.value === 'create') {
      await ProductTableMappingApi.createProductTableMapping(submitData)
      message.success(t('common.createSuccess'))
    } else {
      await ProductTableMappingApi.updateProductTableMapping(submitData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    productId: undefined,
    tableName: undefined,
    type: DEFAULT_DEVTYPE,
    timeField: undefined,
    ignoreField: [] as string[],
  }
  formRef.value?.resetFields()
}
</script>
